import NetConfig from "../NetConfig";
import SendMessage from "../message/SendMessage";
import Service from "./Service";


export default class WebHttpService extends Service {

    private static OK = 4;
    isReady() {
        return true;
    }
    connect(url: string, port?: number) {
        super.connect(url);
        this.onOpen();
    }
    sendData(message: SendMessage) {
        let xhr = this.createXHR();
        let protoID = message.getProtoID();
        let address = this.url;
        let self = this
        xhr.timeout = 15000;
        xhr.ontimeout = function () {
            self.onError(message);
        }
        xhr.onload = function () {
            if (xhr.status >= 200 && xhr.status < 400) {
                var data = xhr.responseText;
                self.onData(data, protoID);
            } else {
                self.onError(message);
            }
        };
        let data = message.getData();
        let method = message.getMethod();

        if (method == NetConfig.GET) {
            address = address + protoID + "?" + data;
            xhr.open(method, address);
            try {
                xhr.send();
            } catch (error) {
                cc.log("get  error ", error);
            }

        } else {
            // post请求
            xhr.open(method, address + protoID);
            try {
                xhr.send(data);
            } catch (error) {
                cc.log("post  error ", error);
            }

        }
    }

    createXHR() {
        // IE7+,Firefox, Opera, Chrome ,Safari
        return new XMLHttpRequest();
    }

}
